<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/16
 * Time: 21:09
 * @link http://www.lmterp.cn
 */

namespace app\common\service\system;


use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\AccountSettings;
use app\common\service\BaseService;
use think\facade\Log;

/**
 * 账号管理服务类
 * Class Account
 * @package app\common\service\system
 */
class AccountService extends BaseService
{
    /**
     * 添加平台
     * @param array $data
     * @return AccountPlatform|bool
     * @date 2020/09/16
     * @author longli
     */
    public function addPlatform($data = [])
    {
        $pData = AccountPlatform::getFilterField($data, '');
        if(empty($pData)) return false;
        $pData = Tools::trim($pData);
        $platform = null;
        if(isset($pData['platform_id'])) $platform = AccountPlatform::get($pData['platform_id']);
        if(isset($pData['code'])) $pData['code'] = strtoupper($pData['code']);
        if(!empty($platform))
        {
            $platform->save($pData);
        }
        else
        {
            $platform = AccountPlatform::create($pData)->refresh();
        }
        return $platform;
    }

    /**
     * 添加账号
     * @param array $data 账号信息
     * @return \app\common\model\Account|bool
     * @date 2020/09/17
     * @author longli
     */
    public function addAccount($data = [])
    {
        $aData = \app\common\model\Account::getFilterField($data, '');
        if(empty($aData)) return false;
        $aData = Tools::trim($aData);
        $account = null;
        if(isset($aData['account_id'])) $account = \app\common\model\Account::get($aData['account_id']);
        if(empty($account) && !empty($aData['platform_id']) && !empty($aData['username']))
            $account = \app\common\model\Account::get(['platform_id' => $aData['platform_id'], 'username' => $aData['username']]);
        if(!empty($account))
        {
            $account->save($aData);
        }
        else
        {
            $account = \app\common\model\Account::create($aData)->refresh();
        }
        return $account;
    }

    /**
     * 添加账号订单配置信息
     * @param array $data 配置信息
     * @return AccountSettings|bool
     * @date 2020/09/17
     * @author longli
     */
    public function addAccountSettings($data = [])
    {
        $sData = AccountSettings::getFilterField($data, '');
        if(empty($sData)) return false;
        $sData = Tools::trim($sData);
        $settings = null;
        if(isset($sData['settings_id'])) $settings = AccountSettings::get($sData['settings_id']);
        if(empty($settings) && isset($sData['account_id'])) $settings = AccountSettings::get(['account_id' => $sData['account_id']]);
        if(!empty($settings))
        {
            $settings->save($sData);
        }
        else
        {
            $settings = AccountSettings::create($sData)->refresh();
        }
        return $settings;
    }

    /**
     * 通过账号ID同步订单信息
     * @param int $accountId 账号id
     * @return bool
     * @date 2020/09/21
     * @author longli
     */
    public function syncOrderByAccount($accountId)
    {
        $account = Account::get($accountId);
        if(empty($account))  throw new \RuntimeException(sprintf("账号【%d】不存在", $accountId));
        $settings = $account->settings;
        if(empty($settings)) throw new \RuntimeException(sprintf("账号【%s】未配置同步信息", $account->username));
        if($settings->status == AccountSettings::STATUS_ING) throw new \RuntimeException(sprintf("账号【%s】正在同步中，请稍后...", $account->username));
        if($settings->status == AccountSettings::STATUS_ERR) throw new \RuntimeException(sprintf("账号【%s】同步失败请重围状态", $account->username));
        $snow = Tools::now();
        $settings->status = AccountSettings::STATUS_ING;
        $settings->start_sync_time = $snow;
        $settings->last_sync_time = $snow;
        $settings->save();
        buildCommandClient()->get("platform/getOrder?account_id={$settings->account_id}");
    }

    /**
     * 重置订单同步状态为未同步
     * @date 2020/09/21
     * @author longli
     */
    public function resetSyncStatus()
    {
        foreach(AccountSettings::where([
            ['is_auto_sync', '=', AccountSettings::AUTO_SYNC_Y],
            ['status', 'not in', [AccountSettings::STATUS_NONE, AccountSettings::STATUS_SUC]]
        ])->select() as $settings)
        {
            $last = strtotime($settings->last_sync_time);
            $hours = $settings->hours * 3600;
            if(time() - $last > $hours)
            {
                Log::info(sprintf("账号【%d】同步失败重置状态为未同步", $settings->account_id));
                $settings->status = AccountSettings::STATUS_NONE;
                $settings->save();
            }
        }
    }


}